package com.atguigu.gmall.realtime.app.func;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.beans.TableProcess;
import org.apache.flink.api.common.state.BroadcastState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.ReadOnlyBroadcastState;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.co.BroadcastProcessFunction;
import org.apache.flink.util.Collector;

import java.sql.*;
import java.util.*;

/**
 * @author Felix
 * @date 2023/11/8
 * 处理关联后的数据，将维度数据过滤出来
 */
public class TableProcessFunction extends BroadcastProcessFunction<JSONObject, TableProcess, JSONObject> {
    private MapStateDescriptor<String, TableProcess> mapStateDescriptor;
    private Map<String,TableProcess> configMap = new HashMap<>();

    public TableProcessFunction(MapStateDescriptor<String, TableProcess> mapStateDescriptor) {
        this.mapStateDescriptor = mapStateDescriptor;
    }

    @Override
    public void open(Configuration parameters) throws Exception {
        //将配置表中的配置信息加载到程序中
        //注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //创建连接
        Connection conn = DriverManager.getConnection("jdbc:mysql://hadoop102:3306/gmall0529_config?" +
            "user=root&password=123456&useUnicode=true&characterEncoding=utf8&serverTimeZone=Asia/Shanghai&useSSL=false");
        //获取数据库操作对象
        String sql = "select * from gmall0529_config.table_process_dim ";
        PreparedStatement ps = conn.prepareStatement(sql);
        //执行SQL语句
        ResultSet rs = ps.executeQuery();
        ResultSetMetaData metaData = rs.getMetaData();

        //处理结果集
        while (rs.next()){
            //定义一个新的json对象，用于接收查询出来的一条数据
            JSONObject jsonObj = new JSONObject();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                String columnName = metaData.getColumnName(i);
                Object columnValue = rs.getObject(i);
                jsonObj.put(columnName,columnValue);
            }
            //将json对象转换为实体类对象
            TableProcess tableProcess = jsonObj.toJavaObject(TableProcess.class);
            //将封装的对象 放到map集合中
            configMap.put(tableProcess.getSourceTable(),tableProcess);
        }
        //释放资源
        rs.close();
        ps.close();
        conn.close();
    }

    //处理主流数据
    @Override
    public void processElement(JSONObject jsonObj, ReadOnlyContext ctx, Collector<JSONObject> out) throws Exception {
        // {"database":"gmall0529","data":{"tm_name":"Redmi","create_time":"2021-12-14 00:00:00","logo_url":"aaa","id":1},"old":{},"type":"update","table":"base_trademark","ts":1699410092}
        // System.out.println(jsonObj);

        //获取当前处理的数据的表名
        String tableName = jsonObj.getString("table");
        //获取广播状态
        ReadOnlyBroadcastState<String, TableProcess> broadcastState = ctx.getBroadcastState(mapStateDescriptor);
        //根据表名到广播状态中获取对应的配置信息
        TableProcess tableProcess = null;

        if((tableProcess = broadcastState.get(tableName)) != null
            ||(tableProcess = configMap.get(tableName)) != null){
            //说明是维度数据，将维度数据传递到下游（只需要传递data部分的内容）
            //{"tm_name":"Redmi","create_time":"2021-12-14 00:00:00","logo_url":"ddd","id":1}
            JSONObject dataJsonObj = jsonObj.getJSONObject("data");

            //在向下游传递数据前，过滤掉不需要的属性
            String sinkColumns = tableProcess.getSinkColumns();
            filterColumn(dataJsonObj,sinkColumns);

            //在向下游传递数据前，补充配置属性
            dataJsonObj.put("table_process",tableProcess);
            //在向下游传递数据前，补充操作类型
            String type = jsonObj.getString("type");
            dataJsonObj.put("type",type);

            // {"tm_name":"Redmi","create_time":"2021-12-14 00:00:00","logo_url":"eeee","id":1,"type":"update","table_process":{"op":"r","sinkColumns":"id,tm_name","sinkFamily":"info","sinkRowKey":"id","sinkTable":"dim_base_trademark","sourceTable":"base_trademark"}}
            out.collect(dataJsonObj);
        }

    }

    //过滤掉不需要传递的字段
    //dataJsonObj:{"tm_name":"Redmi","create_time":"2021-12-14 00:00:00","logo_url":"ddd","id":1}
    //sinkColumns：id,tm_name
    private void filterColumn(JSONObject dataJsonObj, String sinkColumns) {
        String[] columnArr = sinkColumns.split(",");
        List<String> columnList = Arrays.asList(columnArr);
        Set<Map.Entry<String, Object>> entrySet = dataJsonObj.entrySet();
        entrySet.removeIf(entry->!columnList.contains(entry.getKey()));
    }

    //处理广播流数据
    @Override
    public void processBroadcastElement(TableProcess tableProcess, Context ctx, Collector<JSONObject> out) throws Exception {
        //获取对配置表的操作类型
        String op = tableProcess.getOp();
        //获取广播状态
        BroadcastState<String, TableProcess> broadcastState = ctx.getBroadcastState(mapStateDescriptor);
        //获取业务数据库维度表名称作为key
        String key = tableProcess.getSourceTable();

        if("d".equals(op)){
            //将对应的配置信息从广播状态中删除
            broadcastState.remove(key);
            configMap.remove(key);
        }else{
            //将对应的配置信息放到广播状态中
            broadcastState.put(key,tableProcess);
            configMap.put(key,tableProcess);
        }

    }
}
